package com.declum.archon.chunkserver.handler.request;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;

import com.declum.archon.chunkserver.handler.ChunkServerHandler;
import com.declum.archon.chunkserver.server.IChunkServer;

/**
 * This is the Base class for all request handler which can be created for
 * {@link ChunkServerHandler}.
 * 
 * @author Clement
 * 
 */
abstract public class BaseRequestHandler implements IRequest {
	protected IChunkServer		server;
	protected CharsetDecoder	decoder;
	protected CharsetEncoder	encoder;
	protected ByteBuffer		outputBuffer;

	public BaseRequestHandler() {
		this.decoder = Charset.defaultCharset().newDecoder();
		this.encoder = Charset.defaultCharset().newEncoder();
		this.outputBuffer = ByteBuffer.allocate(1024);
	}

	/**
	 * Sets the server instance.
	 */
	@Override
	public final void setServerInstance(IChunkServer server) {
		if (server == null) {
			throw new NullPointerException("");
		}
		this.server = server;
	}

	/**
	 * Sends Acknowledgment packet to the client
	 * 
	 * @see ARCHON-5
	 * @param session
	 */
	protected void sendAcknowledge(IoSession session) {
		ByteBuffer buffer = ByteBuffer.allocate(4);
		buffer.put("ACK".getBytes());
		buffer.flip();
		session.write(buffer);
	}

	/**
	 * Sends Error packet to the client
	 * 
	 * @see ARCHON-5
	 * @param session
	 */
	protected void sendErrorMessage(IoSession session, String message) {
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put("ERR".getBytes());
		buffer.put(message.getBytes());
		buffer.flip();
		session.write(buffer);
	}
}
